package com.linkoog.devtools.websocket.toolwindow.right;

import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import java.awt.*;
import java.util.Map;
import java.util.function.Consumer;

public class WebsocketHeaderDialog extends DialogWrapper {

    private final Project project;
    private JPanel myMainPanel;
    private JTabbedPane tabbedPane1;
    private JTable headerTable;
    private JTable cookieTable;

    private Map<String, String> cookies;
    private Map<String, String> headers;
    private Consumer<Map<String, String>> cookiesConsumer;
    private Consumer<Map<String, String>> headersConsumer;



    public WebsocketHeaderDialog(@NotNull Project project, Map<String, String> cookies, Map<String, String> headers,
                                 Consumer<Map<String, String>> cookiesConsumer, Consumer<Map<String, String>> headersConsumer) {
        super(project, false);
        this.project = project;
        this.cookies = cookies;
        this.headers = headers;
        this.cookiesConsumer = cookiesConsumer;
        this.headersConsumer = headersConsumer;
        if (cookies != null){
            getCookieTable().reloadData(cookies.entrySet().stream().map(e -> new WebsocketHeaderTable.ItemInfo(e.getKey(), e.getValue())).toList());
        }
        if (headers != null){
            getHeaderTable().reloadData(headers.entrySet().stream().map(e -> new WebsocketHeaderTable.ItemInfo(e.getKey(), e.getValue())).toList());
        }
        myMainPanel.setMinimumSize(new Dimension(370, 180));
        init();
    }

    @Override
    protected void doOKAction() {
        if (cookiesConsumer != null){
            cookiesConsumer.accept(getCookieTable().getKeyValue());
        }

        if (headersConsumer != null){
            headersConsumer.accept(getHeaderTable().getKeyValue());
        }
        super.doOKAction();
    }

    @Override
    protected JComponent createCenterPanel() {
        return myMainPanel;
    }

    private void createUIComponents() {
        headerTable = new WebsocketHeaderTable();
        cookieTable = new WebsocketHeaderTable();
    }

    private WebsocketHeaderTable getHeaderTable() {
        return (WebsocketHeaderTable) headerTable;
    }

    private WebsocketHeaderTable getCookieTable() {
        return (WebsocketHeaderTable) cookieTable;
    }
}
